<?php

class Materials_AdminController extends Workset_Controller_Action_Admin {

	function init() {

		//загружаем модуль каталог
        Workset_Module::loadModule('materials');

		parent::init();

        $appHelper = new Materials_Helper_Application();
        Zend_Controller_Action_HelperBroker::addHelper($appHelper);

	}

    //главная страница админки
    function indexAction() {
        try {
			$this->_response->setRedirect('/materials/admin/list-category', 302);
		}
		catch (Exception $e) {
			$this->_response->setException($e);
		}
    }

    function listCategoryAction() {
        $parentId = (int)$this->_getParam('nodeid');
        $refId = (int)$this->_getParam('ref');
        $backUrl = null;

        //url для формирования данных
        if (isset($this->_actionConfig['jqgrid_category_model_url'])) {
            $modelUrlParams = $this->_actionConfig['jqgrid_category_model_url'];
        } else {
            $modelUrlParams = array('action' => 'list-category-model');
        }

        //url для редактирования
        if (isset($this->_actionConfig['jqgrid_category_edit_url'])) {
            $editUrlParams = $this->_actionConfig['jqgrid_category_edit_url'];
        } else {
            $editUrlParams = array('action' => 'ajax-category-operations');
        }

        //backurl для кнопки "назад"
        if (isset($this->_actionConfig['jqgrid_back_url'])) {
            $backUrlParams = $this->_actionConfig['jqgrid_back_url'];
        } else {
            $backUrlParams = null;
        }

        if ($parentId > 0) {
            $category = $this->_helper->application->getCategory($parentId);
            $modelUrlParams['params']['nodeid'] = $editUrlParams['params']['nodeid'] = $category->getId();

            $modelUrl = $this->_helper->url($modelUrlParams);
			$editUrl = $this->_helper->url($editUrlParams);

            if ($backUrlParams) {
                if ($refId > 0) {
                    $backUrlParams['params']['nodeid'] = $refId;
                    $backUrl = $this->_helper->url($backUrlParams);
                } else {
                    $backUrl = $this->_helper->url($backUrlParams);
                }
            }

            $reqParams = array('ref' => ($refId > 0 ? $refId : $parentId));

            if (!$this->_navigationInit && !$this->_getParam('navigationInit')) {

                $category->setUrl('navigation', $backUrl)->setLabel('navigation', $category['name']);
                $this->_addNavItem($category);
            }

        } else {
            $category = null;

            $modelUrl = $this->_helper->url($modelUrlParams);
			$editUrl = $this->_helper->url($editUrlParams);

            $reqParams = array();
        }

        $reqParams['backurl'] = $this->_request->getRequestUri();

        //навигационная панель для грида
        $navGridEnabled = isset($this->_actionConfig['jqgrid_category_navgrid']) && false !== $this->_actionConfig['jqgrid_category_navgrid'];
        $navGridButtons = null;
        $navGridMyButtons = null;

        if ($navGridEnabled) {
            $navGridButtons = (array)$this->_actionConfig['jqgrid_category_navgrid'];

            if (!empty($this->_actionConfig['jqgrid_category_navgrid_buttons']) && is_array($this->_actionConfig['jqgrid_category_navgrid_buttons'])) {
                $navGridMyButtons = $this->_actionConfig['jqgrid_category_navgrid_buttons'];
            }
        }

        $gridOptions = array(
            'caption' => $this->_actionConfig['jqgrid_category_caption'],
            'url' => $modelUrl,
            'mtype' => 'GET',
            'colNames' => array_values($this->_actionConfig['jqgrid_category_col_names']),
            'colModel' => array_values($this->_actionConfig['jqgrid_category_col_model']),
            'sortname' => 'id',
            'sortorder' => "desc",
            'viewrecords' => true,
            'multiselect' => true,
            'editurl'   => $editUrl,
            'treeGrid' => true,
            'treeGridModel' => 'adjacency',
            'treedatatype' => 'json',
            'ExpandColumn' => 'name',
            'ExpandColClick' => true,
            'autowidth' => true,
            'rowNum' => 100,
			//'viewrecords' => false,
            'viewsortcols' => array('name', 'display_title', 'code', 'id'),
			'ondblClickRow' => new Zend_Json_Expr($this->_helper->application->jsFunction('ondblClickRow', array('rowId'), true)),
			'gridComplete' => new Zend_Json_Expr($this->_helper->application->jsFunction('gridComplete', array(
				'opt' => array(
					'buttons' => $navGridMyButtons,
					'qdata' => $reqParams ? $reqParams : null,
				)
			), true)),
        );

        //ссылка на объект помошника
        $this->view->grid = $this->view
                ->JQueryGrid()
                ->setTableId('categoryList')
                ->setPagerId('categoryPager')
                ->setOptions($gridOptions);

        if ($navGridEnabled) {
            $this->view->grid->enableNavGrid($navGridButtons);
        }

		$this->view->grid->jsObject = $this->_helper->application->jsFunctionName();

        //родительская категория
        $this->view->category = $category;

        //ссылка на верхний уровень вложенности
        if ($backUrl) {
            $this->view->backurl = $backUrl;
            $this->view->backurlLabel = $this->_actionConfig['backurl_label'];
        }

        if (!empty($this->_actionConfig['view_script'])) {
            $this->render($this->_actionConfig['view_script']);
        }
    }

    function listCategoryModelAction() {
        $parentId = (int)$this->_getParam('nodeid');

        $page = (int)$this->_getParam('page');
        if ($page < 1) {
           $page = 1;
        }

        $rows = (int)$this->_getParam('rows');
        if ($rows < 1) {
            $rows = Workset_Model_Object_Abstract::ROWS_LIMIT;
        }

        //выбирать только несовпадающие элементы
        $diff = $this->_getParam('diff');
        if ($diff) {
            $diff = $this->_helper->application->getListId($diff);
        }

        //выбирать только совпадающие элементы
        $intersect = $this->_getParam('intersect');
        if ($intersect) {
            $intersect = $this->_helper->application->getListId($intersect);
        }

        //глубина вложенности
		$level = $this->_getParam('n_level');

		if (!isInt($level)) {
			$level = 0;
		} else {
			$level += 1;
		}

        $cols = $this->_helper->application->getList('cols', true);
        $order = $this->_helper->application->getSortOrder();

        $jqGrid = $this->_helper->JQueryGrid;

		$filter = $this->_getParam('filters');
		$filter = $jqGrid->getFilter($filter, $this->_actionConfig['jqgrid_category_col_model']);

        if ($diff) {
            $filter['id not in(?)'] = $diff;
        }

        if ($intersect) {
            $filter['id in(?)'] = $intersect;
        }

        if ($parentId > 0) {
            $category = $this->_helper->application->getCategory($parentId);
            $filter['parent_id = ?'] = $category->getId();
            $categoryList = Materials_Model_Category::getAll($filter, $order, $rows, $page, true);
        } else {
			$level = 0;
            $category = null;
            $filter[] = 'parent_id is null';
            $categoryList = Materials_Model_Category::getAll($filter, $order, $rows, $page, true);
        }

        //dump(ceil($categoryList->getTotalCount() / $rows)); exit;

        $colNames = $this->_helper->utils->arrayValues(
            $this->_actionConfig['jqgrid_category_col_model'], 'index', 1
        );

        if ($cols) {
            $cols = array_intersect($colNames, $cols);
        } else {
            $cols = $colNames;
        }

        $jqGrid->addColumnFormatter('pub_date', function($value) {
            return timestampToDatetime($value);
        });

        $records = $jqGrid->getRecords(
            $categoryList, $page, ceil($categoryList->getTotalCount() / $rows),
            $categoryList->getTotalCount(), $cols
        );

        $categoryList = $categoryList->setKeyIndex('id')->toArray();

        foreach ($records['rows'] as $key => &$record) {
            $category = $categoryList[$record['id']];
            $record['cell'] = array_merge($record['cell'], array(
                $level,
                $category->hasParent() ? $category->getParentId() : 'null',
                !$category->hasChilds(),
                false
            ));
        }

        $this->_helper->json($records, true);
    }

    function ajaxCategoryOperationsAction() {
        $this->_helper->viewRenderer->setNoRender(true);

        $redirectParams = array('nodeid', 'id', 'backurl', 'ref');
		$params = $this->_request->getQuery();
        if (!empty($params)) {
            $params = array_intersect_key($params, array_combine($redirectParams, $redirectParams));
        }

        $actionSwitcher = new Workset_Controller_Plugin_ActionSwitcher('oper', array(
            'add' => array(
                'action' => 'add-category',
                'params' => $params
			),
            'edit' => array(
                'action' => 'edit-category',
                'params' => $params
			),
            'del' => array(
                'action' => 'delete-category',
                'params' => $params
			),
        ));

        $this->getFrontController()->registerPlugin($actionSwitcher);
        $this->_setParam('handlePostDispatch', false);
    }

    function addCategoryAction() {
        $type = 'category';
        $oper = $this->_getParam('oper');
        $outerEdit = !empty($oper) && $this->_request->isXmlHttpRequest() ? true : false;

        $parentId = (int)$this->_getParam('nodeid');
        $parentCategory = null;

        if ($parentId > 0) {
            $parentCategory = $this->_helper->application->getCategory($parentId);
            if (!$parentCategory) {
                return;
            }
        }

        if ($outerEdit) {
            $this->_helper->viewRenderer->setNoRender(true);
        }

        $formConfig = $this->_helper->moduleConfig('forms/'.$type);
        $form = new Workset_Form($formConfig);

        //транслятор формы
        $form->setTranslator(
            $this->_translate,
            $this->_helper->moduleConfig->getConfig(array('lang', $this->_locale, 'validators'), null, true)
        );

        if ($this->_request->isPost()) {
            try {
                $post = $this->_request->getPost();

                //редактирование через внешнюю форму (jqGrid)
                if ($outerEdit) {
                    $post = $this->_helper->utils->addPrefix($post, $type);
                }

                if ($form->isValid($post)) {
                    $values = $form->getValues();
                    $values = $this->_helper->utils->stripPrefix($values, $type);

                    $category = Materials_Model_Category::create($values);
                    $category->setParentId($parentId);
                    $category->save();

                    if (!$this->_request->isXmlHttpRequest()) {
                        $backUrl = $this->_getParam('backurl');
                        if ($backUrl) {
                            $this->_redirect($backUrl);
                        } else {
                            $this->_helper->redirector->gotoSimple('list-'.$type);
                        }
                    } else {
                        return;
                    }
                }

                throw new Workset_Model_Exception($form->getCustomMessages(Workset_Form::ERROR_CODE), Workset_Form::ERROR_CODE);

            } catch (Zend_Exception $e) {
                $this->_helper->application->throwException($e, null, false);
            }
        }

        $backToListUrl = $this->_helper->url('list-'.$type);

        $this->view->form = $form;
        $this->view->backurl = $backToListUrl;
    }

    function editCategoryAction() {
        $categoryId = (int)$this->_getParam('id');

        $category = $this->_helper->application->getCategory($categoryId);

        $oper = $this->_getParam('oper');
        $outerEdit = !empty($oper) && $this->_request->isXmlHttpRequest() ? true : false;

        if ($outerEdit) {
            $this->_helper->viewRenderer->setNoRender(true);
        }

        $formConfig = $this->_helper->moduleConfig('forms/category');
        $form = new Workset_Form($formConfig);

        if ($this->_request->isPost()) {
            try {
                $post = $this->_request->getPost();

                //редактирование через внешнбб форму (jqGrid)
                if ($outerEdit) {
                    $post = $this->_helper->utils->addPrefix($post, 'category');
                }

                if ($form->isValid($post)) {
                    $values = $form->getValues();
                    $values = $this->_helper->utils->stripPrefix($values, 'category');
                    $category->setData($values);
                    $category->save();

                    if (!$this->_request->isXmlHttpRequest()) {
                        if ($category->hasParent()) {
                            $redirect = $this->_helper->url('list-category', null, null, array('nodeid' => $category->getParentId()));
                        } else {
                            $redirect = $this->_helper->url('list-category');
                        }
                        $this->_redirect($redirect);
                    } else {
                        return;
                    }
                }

                throw new Workset_Model_Exception($form->getCustomMessages(Workset_Form::ERROR_CODE), Workset_Form::ERROR_CODE);

            } catch (Zend_Exception $e) {
                $this->_helper->application->throwException($e, null, false);
            }
        } else {
            $data = $category->toArray();
            foreach ($data as $key => $value) {
                $key = 'category_'.$key;
                if ($element = $form->getElement($key)) {
                    $element->setValue($value);
                }
            }
        }

        $this->view->form = $form;
        $this->render('add-category');
    }

    function deleteCategoryAction() {
        $this->_helper->viewRenderer->setNoRender(true);

        $listId = $this->_helper->application->getListId('id', true);
        if (empty($listId)) {
            throw $this->_helper->application->throwException(null, 404);
        }

        $filter = array('id in(?)' => $listId);

        $categoryList = Materials_Model_Category::getAll($filter);

        //удаление
        try {
            foreach ($categoryList as $category) {
                $category->delete();
            }
        } catch (Zend_Exception $e) {
            throw $this->_helper->application->throwException($e);
        }

        //редирект
        if (!$this->_request->isXmlHttpRequest()) {
            if ($category->hasParent()) {
                $redirect = $this->_helper->url('list-category', null, null, array('nodeid' => $category->getParentId()));
            } else {
                $redirect = $this->_helper->url('list-category');
            }
            $this->_redirect($redirect);
        }
    }

    function listMaterialAction() {

        $categoryId = (int)$this->_getParam('nodeid');

        $navGridEnabled = isset($this->_actionConfig['jqgrid_material_navgrid']) && false !== $this->_actionConfig['jqgrid_material_navgrid'];
        $navGridButtons = null;
        $navGridMyButtons = null;

        if ($navGridEnabled) {
            $navGridButtons = (array)$this->_actionConfig['jqgrid_material_navgrid'];

            if (!empty($this->_actionConfig['jqgrid_material_navgrid_buttons']) && is_array($this->_actionConfig['jqgrid_material_navgrid_buttons'])) {
                $navGridMyButtons = $this->_actionConfig['jqgrid_material_navgrid_buttons'];
            }
        }

        $reqParams = array();

        $backUrl = $this->_getParam('backurl');

        if ($categoryId > 0) {

            $category = $this->_helper->application->getCategory($categoryId);

            if (!$backUrl) {
                if ($category->hasParent()) {
                    $backUrl = $this->_helper->url('list-category', null, null, array('nodeid' => $category->getParentId()));
                } else {
                    $backUrl = $this->_helper->url('list-category');
                }
            }

            $modelUrl = $this->_helper->url('list-category-materials-model', null, null, array('intersect' => $category->getId()));

            $this->_addNavItem(array(
                'title' => $category['name'],
                'label' => $category['name'],
                'active' => true,
                'action' => 'edit',
            ));

            $reqParams['nodeid'] = $category->getId();

        } else {
            $modelUrl = $this->_helper->url('list-material-model');

            if (!$backUrl) {
                $backUrl = $this->_helper->url('list-category');
            }
        }

        $this->view->jqgrid = $this->view->JQueryGrid()
                ->setTableId('materialList')
                ->setPagerId('materialPager')
                ->setOptions(array(
                    'caption' => $this->_actionConfig['jqgrid_material_caption'],
                    'url' => $modelUrl,
                    'mtype' => 'GET',
                    'colNames' => array_values($this->_actionConfig['jqgrid_material_col_names']),
                    'colModel' => array_values($this->_actionConfig['jqgrid_material_col_model']),
                    'sortname' => 'id',
                    'sortorder' => "desc",
                    'viewrecords' => true,
                    'multiselect' => true,
                    'editurl'   => $this->_helper->url('ajax-material-operations'),
                    'autowidth' => true,
                    'rowNum' => 20,
                    'ondblClickRow' => new Zend_Json_Expr($this->_helper->application->jsFunction('ondblClickRow', array('rowId'), true)),
                    'gridComplete' => new Zend_Json_Expr($this->_helper->application->jsFunction('gridComplete', null, true)),
                ))
                ->invokeParams(array(
                    'buttons' => $navGridMyButtons,
                    'qdata' => $reqParams ? $reqParams : null,
                ));

        if ($navGridEnabled) {
            $this->view->jqgrid->enableNavGrid($navGridButtons);
        }

		$this->view->jqgrid->jsObject = $this->_helper->application->jsFunctionName();
        $this->view->backUrl = $backUrl;

    }

	public function addCategoryMaterialsAction() {
		$this->_helper->viewRenderer->setNoRender(true);

		$category = $this->_helper->application->getCategory('id', true);

		$listId = $this->_helper->application->getListId('nodeid', true);
        if (empty($listId)) {
            throw $this->_helper->application->throwException(null, 404);
        }

		$filter = array('id in(?)' => $listId);

        $items = Materials_Model_Material::getAll($filter);

        try {
            foreach ($items as $material) {
                $material->linkToObject($category);
            }
        } catch (Zend_Exception $e) {
            throw $this->_helper->application->throwException($e);
        }

        if (!$this->_request->isXmlHttpRequest()) {
            $backUrl = $this->_getParam('backurl');

            if ($backUrl) {
                $redirect = $backUrl;
            } else {
                $redirect = $this->_helper->url('list-material');
            }

            $this->_redirect($redirect);
        }
	}

    public function deleteCategoryMaterialsAction() {
        $this->_helper->viewRenderer->setNoRender(true);

		$category = $this->_helper->application->getCategory('id', true);

		$listId = $this->_helper->application->getListId('nodeid', true);
        if (empty($listId)) {
            throw $this->_helper->application->throwException(null, 404);
        }

		$filter = array('id in(?)' => $listId);

        $items = Materials_Model_Material::getAll($filter);

        try {
            foreach ($items as $material) {
                $material->unlinkObject($category);

                if ($material->getCategoryId() == $category->getId()) {
                    $material['category_id'] = null;
                    $material->save();
                }

            }
        } catch (Zend_Exception $e) {
            throw $this->_helper->application->throwException($e);
        }

        if (!$this->_request->isXmlHttpRequest()) {
            $backUrl = $this->_getParam('backurl');

            if ($backUrl) {
                $redirect = $backUrl;
            } else {
                $redirect = $this->_helper->url('list-material');
            }

            $this->_redirect($redirect);
        }
    }

    public function selectCategoryMaterialsAction() {

        $category = $this->_helper->application->getCategory('nodeid', true);

        $navGridButtons = null;
        $navGridMyButtons = null;

        $navGridButtons = (array)$this->_actionConfig['jqgrid_material_navgrid'];

        if (!empty($this->_actionConfig['jqgrid_material_navgrid_buttons']) && is_array($this->_actionConfig['jqgrid_material_navgrid_buttons'])) {
            $navGridMyButtons = $this->_actionConfig['jqgrid_material_navgrid_buttons'];
        }

        $reqParams = array(
			'backurl' => $this->_request->getRequestUri(),
			'id' => $category->getId()
		);

        $modelUrl = $this->_helper->url('list-category-materials-model', null, null, array('diff' => $category->getId()));

        $this->view->jqgrid = $this->view->JQueryGrid()
                ->setTableId('materialList')
                ->setPagerId('materialPager')
                ->setOptions(array(
                    'caption' => $this->_actionConfig['jqgrid_material_caption'],
                    'url' => $modelUrl,
                    'mtype' => 'GET',
                    'colNames' => array_values($this->_actionConfig['jqgrid_material_col_names']),
                    'colModel' => array_values($this->_actionConfig['jqgrid_material_col_model']),
                    'sortname' => 'id',
                    'sortorder' => "desc",
                    'viewrecords' => true,
                    'multiselect' => true,
                    'editurl'   => $this->_helper->url('ajax-material-operations'),
                    'autowidth' => true,
                    'rowNum' => 20,
                    'ondblClickRow' => new Zend_Json_Expr($this->_helper->application->jsFunction('ondblClickRow', array('rowId'), true)),
                    'gridComplete' => new Zend_Json_Expr($this->_helper->application->jsFunction('gridComplete', null, true)),
                ))
                ->enableNavGrid(array(
                    'all' => false,
                    'search' => true,
                    'refresh' => true
                ))
                ->invokeParams(array(
                    'buttons' => $navGridMyButtons,
                    'qdata' => $reqParams ? $reqParams : null,
                ))
                ->enableNavGrid($navGridButtons);

		$this->view->jqgrid->jsObject = $this->_helper->application->jsFunctionName();
		$this->view->backUrl = $this->_helper->url('list-category');

    }

    public function unselectCategoryMaterialsAction() {

        $category = $this->_helper->application->getCategory('nodeid', true);

        $navGridButtons = null;
        $navGridMyButtons = null;

        $navGridButtons = (array)$this->_actionConfig['jqgrid_material_navgrid'];

        if (!empty($this->_actionConfig['jqgrid_material_navgrid_buttons']) && is_array($this->_actionConfig['jqgrid_material_navgrid_buttons'])) {
            $navGridMyButtons = $this->_actionConfig['jqgrid_material_navgrid_buttons'];
        }

        $reqParams = array(
			'backurl' => $this->_request->getRequestUri(),
			'id' => $category->getId()
		);

        $modelUrl = $this->_helper->url('list-category-materials-model', null, null, array('intersect' => $category->getId()));

        $this->view->jqgrid = $this->view->JQueryGrid()
                ->setTableId('materialList')
                ->setPagerId('materialPager')
                ->setOptions(array(
                    'caption' => $this->_actionConfig['jqgrid_material_caption'],
                    'url' => $modelUrl,
                    'mtype' => 'GET',
                    'colNames' => array_values($this->_actionConfig['jqgrid_material_col_names']),
                    'colModel' => array_values($this->_actionConfig['jqgrid_material_col_model']),
                    'sortname' => 'id',
                    'sortorder' => "desc",
                    'viewrecords' => true,
                    'multiselect' => true,
                    'editurl'   => $this->_helper->url('ajax-material-operations'),
                    'autowidth' => true,
                    'rowNum' => 20,
                    'ondblClickRow' => new Zend_Json_Expr($this->_helper->application->jsFunction('ondblClickRow', array('rowId'), true)),
                    'gridComplete' => new Zend_Json_Expr($this->_helper->application->jsFunction('gridComplete', null, true)),
                ))
                ->enableNavGrid(array(
                    'all' => false,
                    'search' => true,
                    'refresh' => true
                ))
                ->invokeParams(array(
                    'buttons' => $navGridMyButtons,
                    'qdata' => $reqParams ? $reqParams : null,
                ))
                ->enableNavGrid($navGridButtons);

		$this->view->jqgrid->jsObject = $this->_helper->application->jsFunctionName();
		$this->view->backUrl = $this->_helper->url('list-category');

        $this->render('select-category-materials');

    }

    public function listMaterialModelAction() {
        $categoryId = (int)$this->_getParam('nodeid');

        //выбирать только несовпадающие элементы
        $diff = $this->_getParam('diff');
        if ($diff) {
            $diff = $this->_helper->application->getListId($diff);
        }

        //выбирать только совпадающие элементы
        $intersect = $this->_getParam('intersect');
        if ($intersect) {
            $intersect = $this->_helper->application->getListId($intersect);
        }

        $page = (int)$this->_getParam('page');
        if ($page < 1) {
           $page = 1;
        }

        $rows = (int)$this->_getParam('rows');
        if ($rows < 1) {
            $rows = Workset_Model_Object_Abstract::ROWS_LIMIT;
        }

        $cols = $this->_helper->application->getList('cols', true);

        $order = $this->_helper->application->getSortOrder();

        $jqGrid = $this->_helper->JQueryGrid;

		$filter = $this->_getParam('filters');
		$filter = $jqGrid->getFilter($filter, $this->_actionConfig['jqgrid_material_col_model']);

        if ($diff) {
            $filter['id not in(?)'] = $diff;
        }

        if ($intersect) {
            $filter['id in(?)'] = $intersect;
        }

        if ($categoryId > 0) {
            $filter['category_id = ?'] = $categoryId;
        }

        $colNames = $this->_helper->utils->arrayValues(
            $this->_actionConfig['jqgrid_material_col_model'], 'index', 1
        );

        if ($cols) {
            $cols = array_intersect($colNames, $cols);
        } else {
            $cols = $colNames;
        }

        $items = Materials_Model_Material::getAll($filter, $order, $rows, $page, true);

        $jqGrid->addColumnFormatter('created', function($value) {
            return timestampToDatetime($value);
        });

        $records = $jqGrid->getRecords(
            $items, $page, ceil($items->getTotalCount() / $rows),
            $items->getTotalCount(), $cols
        );

        $this->_helper->json($records, true);
    }

	public function listCategoryMaterialsModelAction() {

        //выбирать только несовпадающие элементы
        $diff = $this->_getParam('diff');
        if ($diff) {
            $diff = $this->_helper->application->getListId($diff);
        }

        //выбирать только совпадающие элементы
        $intersect = $this->_getParam('intersect');
        if ($intersect) {
            $intersect = $this->_helper->application->getListId($intersect);
        }

        $page = (int)$this->_getParam('page');
        if ($page < 1) {
           $page = 1;
        }

        $rows = (int)$this->_getParam('rows');
        if ($rows < 1) {
            $rows = Workset_Model_Object_Abstract::ROWS_LIMIT;
        }

        $cols = $this->_helper->application->getList('cols', true);

        $order = $this->_helper->application->getSortOrder();

        $jqGrid = $this->_helper->JQueryGrid;
        $jqGrid->addColumnFormatter('created', function($value) {
            return timestampToDatetime($value);
        });

		$filter = $this->_getParam('filters');
		$filter = $jqGrid->getFilter($filter, $this->_actionConfig['jqgrid_material_col_model']);

        $colNames = $this->_helper->utils->arrayValues(
            $this->_actionConfig['jqgrid_material_col_model'], 'index', 1
        );

        if ($cols) {
            $cols = array_intersect($colNames, $cols);
        } else {
            $cols = $colNames;
        }

        $items = Materials_Model_Category::getCategoryMaterials($diff, $intersect, $filter, $order, $rows, $page, true);

        $records = $jqGrid->getRecords(
            $items, $page, ceil($items->getTotalCount() / $rows),
            $items->getTotalCount(), $cols
        );

        $this->_helper->json($records, true);
	}

    public function addMaterialAction() {
		$categoryId = $this->_getParam('nodeid');

		//предлагаем выбрать раздел
        if (null === $categoryId) {
            $this->_redirect(
                $this->_helper->url(
                    'select-category', null, null,
                    array('backurl' => $this->_request->getRequestUri())
                ),
                array('code' => 301)
            );

        } elseif ($categoryId < 1) {
			$this->_helper->application->throwException('Undefined category ID', 404);
		} else {
            $categoryId = (int)$categoryId;
        }

		try {
			$category = Materials_Model_Category::getInstance($categoryId);
		} catch (Zend_Exception $e) {
			$this->_helper->application->throwException($e, 404);
		}

        //конфинг с описанием блоков и полей формы
        $contentOptions = $this->_actionConfig['content'];

        //нужна ли привязка к категориям и объектам каталога
        $attachCatalogueCategory = false;
        $attachCatalogueObject = false;

        if (!empty($this->_actionConfig['scripts']['catalogue'])) {
            Workset_Module::loadModule('catalogue');

            $attachCatalogueCategory = !empty($this->_actionConfig['scripts']['catalogue']['attach_catalogue_category']);
            $attachCatalogueObject = !empty($this->_actionConfig['scripts']['catalogue']['attach_catalogue_object']);
        }

        //нужна ли привязка к меткам
        $attachLabels = false;

        if (!empty($this->_actionConfig['scripts']['labels'])) {
            $attachLabels = !empty($this->_actionConfig['scripts']['labels']['attach_labels']);
        }

        $formConfig = $this->_helper->moduleConfig('forms/material');
        $form = new Materials_Form_Material($formConfig);

		$form->addActionParams(array('nodeid' => $categoryId));

        //транслятор формы
        $form->setTranslator(
            $this->_translate,
            $this->_helper->moduleConfig->getConfig(array('lang', $this->_locale, 'validators'), null, true)
        );

        //список блоков
        //$contentBlocks = $this->_getContentBlocks($contentOptions);
        $contentBlocks = $this->_helper->application->getContentOptions($contentOptions);
        $dynamicBlocks = array();

        $uploadedFiles = array();

        foreach ($contentBlocks as $block) {
            if (!empty($block['multiple'])) {
                $dynamicBlocks[] = $block;
            }
        }

        if ($this->getRequest()->isPost()) {

            $post = $this->getRequest()->getPost();

			$categories = array();
			$objects = array();
            $labels = array();

            $redirect = isset($post['qsave']);

            if ($this->_actionConfig['upload_files']) {
                $uploadedFiles = $this->_helper->fileTransfer(null, null, false);
                $uploadedFiles = $this->_helper->application->getUploadedFiles($contentBlocks, $uploadedFiles);
            }

			if ($attachCatalogueCategory && isset($post['catalogue']['category'])) {
				$categories = (array)$post['catalogue']['category'];
				$categories = array_map('intval', $categories);
			}

			if ($attachCatalogueObject && isset($post['catalogue']['object'])) {
				$objects = (array)$post['catalogue']['object'];
				$objects = array_map('intval', $objects);
			}

            if ($attachLabels && isset($post['labels'])) {
                $labels = (array)$post['labels'];
				$labels = array_map('intval', $labels);
            }

			try {

                $contentBlocks = $this->_helper->application->getPostContent($contentBlocks, $post, $uploadedFiles);

                if ($form->isValid($post)) {

                    $values = $form->getValues();
                    $values = $this->_helper->utils->stripPrefix($values, 'material');
                    //dump($values);

                    arrayFilter($uploadedFiles, function($val) {
                        return isNotEmpty($val);
                    }, true);

					$values = array_merge($values, array(
                        'serialize' => $this->_actionConfig['serialize'],
                        'category_id' => $category->getId(),
                        'files' => count($uploadedFiles) > 0 ? 1 : 0
					));

                    $content = array();

                    foreach ($contentBlocks as $key => $block) {

                        $name = $block['name'];

                        if (!empty($block['multiple'])) {
                            $name .= "_".$key;
                        }

                        $contentBlock = array();

                        foreach ($block['items'] as $item) {
                            $contentBlock[ $item['name'] ] = array(
                                'type' => $item['type'],
                                $item['value']
                            );
                        }

                        $content[ $name ] = array(
                            'type' => $block['name'],
                            $contentBlock
                        );
                    }

                    $block = new Materials_Model_Material_Block($content);

                    $material = Materials_Model_Material::create($values);
                    $material->setContent($block);

                    if ($material->save()) {

                        //сохранение категорий из каталога
						if (!empty($categories)) {

							$observer = new Materials_Model_Material_Observer_Catalogue_CategoryRelation();
							$material->attach($observer);

							$categories = Catalogue_Model_Category::getAll(array(
								'id in(?)' => array_values($categories)
							));

							foreach ($categories as $category) {
								$material->linkToObject($category);
							}
						}

                        //сохранение меток
                        if (!empty($labels)) {
                            $labels = Materials_Model_Label::getAll(array(
								'id in(?)' => array_values($labels)
							));

							foreach ($labels as $label) {
								$material->linkToObject($label);
							}
                        }

                        if (!$this->_request->isXmlHttpRequest()) {
                            if ($redirect) {
                                $backUrl = $this->_getParam('backurl');
                                if ($backUrl) {
                                    $this->_redirect($backUrl);
                                } else {
                                    $this->_redirect(
                                        $this->_helper->url('list-material', null, null, ($categoryId > 0) ? array('nodeid' => $categoryId) : null)
                                    );
                                }
                            } else {
                                $redirect = $this->_actionConfig['redirect_to_edit'];
                                $redirect['params'] = array('id' => $material->getId());

                                $this->_redirect(
                                    $this->_helper->url($redirect)
                                );
                            }
                        } else {
							return;
						}
                    }
                }

                throw new Workset_Model_Exception($form->getCustomMessages(Workset_Form::ERROR_CODE), Workset_Form::ERROR_CODE);

			} catch (Zend_Exception $e) {
				$this->_helper->application->throwException($e, null, false);
			}
        }

        $this->view->form = $form;
        $this->view->staticContentBlocks = array();
        $this->view->dynamicContentBlocks = $dynamicBlocks;
        $this->view->hasDynamicContent = !empty($dynamicBlocks);
		$this->view->attachCatalogueCategory = $attachCatalogueCategory;
		$this->view->attachCatalogueObject = $attachCatalogueObject;

        foreach ($contentBlocks as $block) {
            if (empty($block['hidden'])) {

                $block['html_elements'] = array();
				$block['id'] = $block['name'].'-'.( !empty($block['multiple']) ? $block['index'] : 0 );

                foreach ($block['items'] as $key => $item) {

                    $name = $block['name'] .( !empty($block['multiple']) ? '[' .$block['index']. ']' : '' ). '[' . $item['name'] . ']';

                    switch ($item['type']) {
                        case 'text':
                            $block['html_elements'][$key] = $this->view->formText($name, $item['value'], $item['attrs']);
                            break;

                        case 'textarea':
                            $block['html_elements'][$key] = $this->view->formTextarea($name, $item['value'], $item['attrs']);
                            break;

                        case 'file':
                        case 'image':
                            $block['html_elements'][$key] = $this->view->formFile($name, $item['attrs']);
                            break;
                    }
                }

                $orderIndex = !empty($block['multiple']) ? $block['index'] : 0;
                $orderName = 'order'. '['. $block['name'] .'][' .$orderIndex. ']';
                $block['html_elements']['order'] = $this->view->formHidden($orderName, $block['index']);

                $this->view->staticContentBlocks[] = $block;
            }
        }

        $scripts = array();
        $content = array();

        foreach ((array)$this->_actionConfig['scripts'] as $params) {
            if (isset($params['script'])) {
                $script = $this->getViewScript($params['script']);
                if (isset($params['position']) && $params['position'] == 'top') {
                    array_unshift($scripts, $script);
                } else {
                    $scripts[] = $script;
                }
            }
        }

		foreach ($scripts as $script) {
            $content[] = $this->initView()->render($script);
		}

        $this->view->content = $content;

    }

	function editMaterialAction() {
        $materialId = (int)$this->_getParam('id');
        $categoryId = (int)$this->_getParam('nodeid');
        $changeCategory = (int)$this->_getParam('change_category');

        $material = Materials_Model_Material::getInstance($materialId);

        $category = $material->getCategory();
        $selectedCategory = null;

        $contentOptions = $this->_actionConfig['content'];

		$contentOptionsNames = array();
        foreach ($contentOptions as $key => $spec) {
            $contentOptionsNames[ $spec['type'] ] = $key;
        }

        $materialContent = $material->getContent();

		$materialContentOptions = array();
		$uploadedFiles = array();

        //нужна ли привязка к категориям и объектам каталога
        $attachCatalogueCategory = false;
        $attachCatalogueObject = false;

        if (!empty($this->_actionConfig['scripts']['catalogue'])) {
            Workset_Module::loadModule('catalogue');

            $attachCatalogueCategory = !empty($this->_actionConfig['scripts']['catalogue']['attach_catalogue_category']);
            $attachCatalogueObject = !empty($this->_actionConfig['scripts']['catalogue']['attach_catalogue_object']);

        }

        //нужна ли привязка к меткам
        $attachLabels = false;

        if (!empty($this->_actionConfig['scripts']['labels'])) {
            $attachLabels = !empty($this->_actionConfig['scripts']['labels']['attach_labels']);
        }

		$this->_addNavItem(array(
            'title' => $material->getTitle(),
            'label' => $material->getTitle(),
            'active' => true,
            'action' => 'edit',
        ));

		//$dynamicBlocks = $this->_getContentBlocks($contentOptions);
		$dynamicBlocks = $this->_helper->application->getContentOptions($contentOptions);
		foreach ($dynamicBlocks as $key => $block) {
            if (empty($block['multiple'])) {
				unset($dynamicBlocks[$key]);
            }
        }

        $formConfig = $this->_helper->moduleConfig('forms/material');
        $form = new Materials_Form_Material($formConfig);

        //устанавливаем категорию
        if ($categoryId > 0 && $changeCategory > 0) {
            $form->addActionParams(array('nodeid' => $categoryId, 'change_category' => $changeCategory));

            if (!$category || $categoryId != $category->getId()) {
                $selectedCategory = $this->_helper->application->getCategory($categoryId);
            }
        }

        //транслятор формы
        $form->setTranslator(
            $this->_translate,
            $this->_helper->moduleConfig->getConfig(array('lang', $this->_locale, 'validators'), null, true)
        );

        if ($this->getRequest()->isPost()) {
            $post = $this->getRequest()->getPost();

			$categories = array();
			$curCategories = array();
			$oldCategories = array();

			$objects = array();
			$curObjects = array();
			$oldObjects = array();

            $labels = array();
            $curLabels = array();
            $oldLabels = array();

			$oldFiles = array();
			$curFiles = array();

            $redirect = isset($post['qsave']);

			//добавление категорий каталога
			if ($attachCatalogueCategory) {

				$storedCategories = $material->getStorage()
											 ->getCatalogueCategories($material)
											 ->setKeyIndex('id')
											 ->toArray();

				if (isset($post['catalogue']['category'])) {
					$categories = (array)$post['catalogue']['category'];
					$categories = array_map('intval', $categories);
				}

				if ($storedCategories) {
					$oldCategories = array_diff(array_keys($storedCategories), $categories);
					$curCategories = array_diff($categories, array_keys($storedCategories));
				} else {
					$curCategories = $categories;
				}
			}

			//добавление объектов каталога
			if ($attachCatalogueObject && isset($post['catalogue']['object'])) {
				$objects = (array)$post['catalogue']['object'];
				$objects = array_map('intval', $objects);
			}

            //добавление меток
            if ($attachLabels) {

                $storedLabels = $material->getLabels()->setKeyIndex('id')->toArray();

                if (isset($post['labels'])) {
                    $labels = (array) $post['labels'];
                    $labels = array_map('intval', $labels);
                }

                if ($storedLabels) {
                    $oldLabels = array_diff(array_keys($storedLabels), $labels);
                    $curLabels = array_diff($labels, array_keys($storedLabels));
                } else {
                    $curLabels = $labels;
                }
            }

			$contentBlocks = $this->_helper->application->getContentOptions($contentOptions);

			if ($this->_actionConfig['upload_files']) {
				$uploadedFiles = $this->_helper->fileTransfer(null, null, false);
				$uploadedFiles = $this->_helper->application->getUploadedFiles($contentBlocks, $uploadedFiles);

				//сохраненные файлы
				$fileContent = $materialContent->filter(Materials_Model_Material::getFileTypes())->toArray();
                $fileContent = array_filter($fileContent, function($val) {
                   return isNotEmpty($val);
                });

				$tmp = array();
				foreach ($uploadedFiles as $name => $data) {
					if (is_array($data)) {
						foreach ($data as $key => $file) {
							if (isInt($key)) {
								$tmp[ $name.'_'.$key ] = $file;
							} else {
								$tmp[$name][$key] = $file;
							}
						}
					}
				}

                $matches = $tmp;

                arrayFilter($matches, function($val) {

                    if (is_array($val)) {
                        foreach ($val as $key => $value) {
                            if (empty($value)) {
                                unset($val[$key]);
                            }
                        }
                    }

					return isNotEmpty($val);

				}, true );

				$filesReplaced = arrayIntersectKey($fileContent, $matches);

				$filesDeleted = arrayDiffKey($fileContent, $tmp, true);

				//список удаляемых файлов
				$oldFiles = arrayMerge($filesReplaced, $filesDeleted);
				$oldFiles = arrayStraight($oldFiles, 1);

                $tmp = arrayDiffKey($fileContent, $matches);

				if ($tmp) {

					foreach ($tmp as $name => $data) {
						if (isset($fileContent[$name])) {
							if (preg_match("/([a-zA-Z0-9\-_]+)\_([\d]+)$/", $name, $m)) {
								$curFiles[$m[1]][$m[2]] = $data;
							} else {
								$curFiles[$name] = $data;
							}
						}
					}
				}

				$curFiles = arrayMerge($curFiles, $uploadedFiles);
			}

			//dump($uploadedFiles); exit;

            $contentBlocks = $this->_helper->application->getPostContent($contentBlocks, $post, $curFiles);

			try {

                if ($form->isValid($post)) {

					$values = $form->getValues();
                    $values = $this->_helper->utils->stripPrefix($values, 'material');

					if ($selectedCategory) {
                        $values['category_id'] = $selectedCategory->getId();
                        $category = $selectedCategory;
                        $selectedCategory = null;
                    }

                    if ($curFiles) {
                        arrayFilter($curFiles, function($val) {
                            return isNotEmpty($val);
                        }, true);
                    }

                    $values['files'] = count($curFiles) > 0 ? 1 : 0;

                    $content = array();

                    //собираем структуру контента из POST
                    foreach ($contentBlocks as $index => $block) {

                        $name = $block['name'];

                        if (!empty($block['multiple'])) {
                            $name .= "_".$index;
                        }

                        $contentBlock = array();

                        foreach ($block['items'] as $item) {
                            $contentBlock[ $item['name'] ] = array(
                                'type' => $item['type'],
                                $item['value']
                            );
                        }

                        $content[ $name ] = array(
                            'type' => $block['name'],
                            $contentBlock
                        );
                    }

					$block = new Materials_Model_Material_Block($content);

					$material->setData($values);
                    $material->setContent($block);

                    if ($material->save()) {

						$material->dropFiles($oldFiles);

                        //сохранение категорий каталога у материала
						if ($curCategories || $oldCategories) {

							$observer = new Materials_Model_Material_Observer_Catalogue_CategoryRelation();
							$material->attach($observer);

							if ($curCategories) {
								$curCategories = Catalogue_Model_Category::getAll(array(
									'id in(?)' => $curCategories
								));

								foreach ($curCategories as $category) {
									$material->linkToObject($category);
								}
							}

							if ($oldCategories) {
								$oldCategories = Catalogue_Model_Category::getAll(array(
									'id in(?)' => $oldCategories
								));

								foreach ($oldCategories as $category) {
									$material->unlinkObject($category);
								}
							}
						}

                        //сохранение меток материала
                        if ($curLabels || $oldLabels) {

							if ($curLabels) {
								$curLabels = Materials_Model_Label::getAll(array(
									'id in(?)' => $curLabels
								));

								foreach ($curLabels as $label) {
									$material->linkToObject($label);
								}
							}

							if ($oldLabels) {
								$oldLabels = Materials_Model_Label::getAll(array(
									'id in(?)' => $oldLabels
								));

								foreach ($oldLabels as $label) {
									$material->unlinkObject($label);
								}
							}
						}


                        if (!$this->_request->isXmlHttpRequest()) {
                            if ($redirect) {
                                $backUrl = $this->_getParam('backurl');
                                if ($backUrl) {
                                    $this->_redirect($backUrl);
                                } else {
                                    $this->_redirect(
                                        $this->_helper->url('list-material')
                                    );
                                }
                            } else {
                                $redirect = $this->_actionConfig['redirect_to_edit'];
                                $redirect['params'] = array('id' => $material->getId());

                                $this->_redirect(
                                    $this->_helper->url($redirect)
                                );
                            }

                        }
                    }
                }

                //для вывода текущего списка категорий
				if ($attachCatalogueCategory) {
					$this->view->catalogueCategories = Catalogue_Model_Category::getAll(array(
						'id in(?)' => array_values($categories)
					))->toArray(array('name', 'id'));
				}

                //для вывода текущего списка меток
                if ($attachLabels) {
					$this->view->catalogueCategories = Materials_Model_Label::getAll(array(
						'id in(?)' => array_values($labels)
					))->toArray(array('name', 'id'));
				}

                throw new Workset_Model_Exception($form->getCustomMessages(Workset_Form::ERROR_CODE), Workset_Form::ERROR_CODE);

            } catch (Zend_Exception $e) {
				$this->_helper->application->throwException($e, null, false);
			}

        } else {

            $it = new RecursiveIteratorIterator($materialContent, RecursiveIteratorIterator::SELF_FIRST);
            $it->setMaxDepth(0);

            $existsOptions = array();

            foreach ($it as $item) {

                $type = $item->getType();

                $options = null;

                //ищем опции для сохраненных значений из конфига
                if (isset($contentOptionsNames[$type])) {
                    $options = $contentOptions[ $contentOptionsNames[$type] ];

                    foreach ($options['elements'] as $key => $data) {
                        unset($options['elements'][$key]);
                        $options['elements'][ $data['fields']['name'] ] = $data;
                    }

                    $existsOptions[] = $type;
                }

                //устанавливаем сохраненные значения
                if ($options) {
                    foreach ($item as $name => $block) {
                        $value = $block->toArray();

                        if (is_array($value) && !in_array($block->getType(), Materials_Model_Material::getFileTypes())) {
                            $value = current($value);
                        }

                        if (isset($options['elements'][$name])) {
                            $options['elements'][$name]['fields']['value'] = $value;
                        }
                    }
                }

                $materialContentOptions[] = $options;
            }

            //новые опции, которые не сохранены у материала
            $existsOptions = array_unique($existsOptions);
            $contentOptionsNames = array_diff_key( $contentOptionsNames, array_flip($existsOptions) );

            foreach ($contentOptionsNames as $type => $index) {
                if ($contentOptions[$index]['hidden'] == false) {
                    $materialContentOptions[] = $contentOptions[$index];
                }
            }

            $contentBlocks = $this->_helper->application->getContentOptions($materialContentOptions);

            foreach ($contentBlocks as $key => $block) {
                $contentBlocks[$key]['hidden'] = false;
            }

			$data = Materials_Model_Material::getOutputData($material);
            foreach ($data as $key => $value) {

				if ($key == 'content') {
					continue;
				}

                $key = 'material_'.$key;
                if ($element = $form->getElement($key)) {
                    $element->setValue($value);
                }
            }

			//список сохраненных категорий каталога
			if ($attachCatalogueCategory) {

				$this->view->catalogueCategories =  $material->getStorage()
										->getCatalogueCategories($material)
										->toArray(array('name', 'id'));
			}

            //список меток
			if ($attachLabels) {
				$this->view->labels =  $material->getLabels()->toArray(array('name', 'id'));
			}

        }

        $changeUrl = null;

        if ($category) {
            if ($category->hasParent()) {
                $category->setUrl('list', $this->_helper->url('list-category', null, null, array('nodeid' => $category->getParentId())));
                $changeUrl = $this->_helper->url('select-category', null, null, array(
                    'nodeid' => $category->getParentId(),
                    'change_category' => 1,
                    'backurl' => $this->_helper->url('edit-material', null, null, array(
                        'id' => $material->getId(),
                        'change_category' => 1,
                    ))
                ));
            } else {
                $category->setUrl('list', $this->_helper->url('list-category'));
            }
        }

        if (!$changeUrl) {
            $changeUrl = $this->_helper->url('select-category', null, null, array(
                'backurl' => $this->_helper->url('edit-material', null, null, array(
                    'id' => $material->getId(),
                    'change_category' => 1,
                ))
            ));
        }

        if ($selectedCategory) {
            if ($selectedCategory->hasParent()) {
                $selectedCategory->setUrl('list', $this->_helper->url('list-category', null, null, array('nodeid' => $selectedCategory->getParentId())));
            } else {
                $selectedCategory->setUrl('list', $this->_helper->url('list-category'));
            }
        }

		$this->view->form = $form;

        $this->view->staticContentBlocks = array();
        $this->view->dynamicContentBlocks = $dynamicBlocks;
        $this->view->hasDynamicContent = !empty($dynamicBlocks);
		$this->view->material = $material;
        $this->view->category = $category;
        $this->view->selectedCategory = $selectedCategory;
        $this->view->categoryChangeUrl = $changeUrl;
		$this->view->attachCatalogueCategory = $attachCatalogueCategory;
		$this->view->attachCatalogueObject = $attachCatalogueObject;

		foreach ($contentBlocks as $block) {
            if (empty($block['hidden'])) {

                $block['html_elements'] = array();
				$block['id'] = $block['name'].'-'.( !empty($block['multiple']) ? $block['index'] : 0 );

                foreach ($block['items'] as $key => $item) {

                    switch ($item['type']) {
                        case 'text':
							$name = $block['name'] .( !empty($block['multiple']) ? '[' .$block['index']. ']' : '' ). '[' . $item['name'] . ']';
                            $block['html_elements'][$key] = $this->view->formText($name, $item['value'], $item['attrs']);
                            break;

                        case 'textarea':
							$name = $block['name'] .( !empty($block['multiple']) ? '[' .$block['index']. ']' : '' ). '[' . $item['name'] . ']';
                            $block['html_elements'][$key] = $this->view->formTextarea($name, $item['value'], $item['attrs']);
                            break;

                        case 'file':
                        case 'image':
                            $block['items'][$key]['value']['shortpath'] = (string)$this->_helper->imageUri($item['value']['shortpath'], 710, 399, null, 1);

							$name = $block['name'] .( !empty($block['multiple']) ? '_' .$block['index'] : '' ). '[' . $item['name'] . ']';
                            $block['html_elements'][$key] = $this->view->formFile($name, $item['attrs']);
                            break;
                    }
                }

                $orderIndex = !empty($block['multiple']) ? $block['index'] : 0;
                $orderName = 'order'. '['. $block['name'] .'][' .$orderIndex. ']';
                $block['html_elements']['order'] = $this->view->formHidden($orderName, $block['index']);

                $this->view->staticContentBlocks[] = $block;
            }
        }

		$scripts = array();
        $content = array();

        foreach ((array)$this->_actionConfig['scripts'] as $params) {
            if (isset($params['script'])) {
                $script = $this->getViewScript($params['script']);
                if (isset($params['position']) && $params['position'] == 'top') {
                    array_unshift($scripts, $script);
                } else {
                    $scripts[] = $script;
                }
            }
        }

		foreach ($scripts as $script) {
            $content[] = $this->initView()->render($script);
		}

        $this->view->content = $content;

        $this->render($this->_request->getActionName());
        $this->render('add-material');
	}

	function deleteMaterialAction() {
		$this->_helper->viewRenderer->setNoRender(true);

        $listId = $this->_helper->application->getListId('id', true);
        if (empty($listId)) {
            throw $this->_helper->application->throwException(null, 404);
        }

        $filter = array('id in(?)' => $listId);

        $itemList = Materials_Model_Material::getAll($filter);

        try {
            foreach ($itemList as $object) {
                $object->delete();
            }
        } catch (Zend_Exception $e) {
            throw $this->_helper->application->throwException($e);
        }

        if (!$this->_request->isXmlHttpRequest()) {
            $backUrl = $this->_getParam('backurl');

            if ($backUrl) {
                $redirect = $backUrl;
            } else {
                $redirect = $this->_helper->url('list-material');
            }

            $this->_redirect($redirect);
        }
	}

    function ajaxMaterialOperationsAction() {
        $this->_helper->viewRenderer->setNoRender(true);

        $redirectParams = array('nodeid', 'id', 'backurl', 'ref');
		$params = $this->_request->getQuery();
        if (!empty($params)) {
            $params = array_intersect_key($params, array_combine($redirectParams, $redirectParams));
        }

        $actionSwitcher = new Workset_Controller_Plugin_ActionSwitcher('oper', array(
            'del' => array(
                'action' => 'delete-material',
                'params' => $params
			),
        ));

        $this->getFrontController()->registerPlugin($actionSwitcher);
        $this->_setParam('handlePostDispatch', false);
    }

	function listCommentAction() {
        $this->view->jqgrid = $this->view->JQueryGrid()
                ->setTableId('commentList')
                ->setPagerId('commentPager')
                ->setOptions(array(
                    'caption' => $this->_actionConfig['jqgrid_comment_caption'],
                    'url' => $this->_helper->url('list-comment-model'),
                    'mtype' => 'GET',
                    'colNames' => array_values($this->_actionConfig['jqgrid_comment_col_names']),
                    'colModel' => array_values($this->_actionConfig['jqgrid_comment_col_model']),
                    'sortname' => 'id',
                    'sortorder' => "desc",
                    'viewrecords' => true,
                    'multiselect' => true,
                    'editurl'   => $this->_helper->url('ajax-comment-operations'),
                    'autowidth' => true,
                    'rowNum' => 20,
                ))
                ->enableNavGrid(array(
                    'add' => false,
                    'del' => true,
                    'edit' => true,
					'search' => true
                ));

		$this->view->jqgrid->jsObject = $this->_helper->application->jsFunctionName();
	}

	function listCommentModelAction() {
		//выбирать только несовпадающие элементы
        $diff = $this->_getParam('diff');
        if ($diff) {
            $diff = $this->_helper->application->getListId($diff);
        }

        //выбирать только совпадающие элементы
        $intersect = $this->_getParam('intersect');
        if ($intersect) {
            $intersect = $this->_helper->application->getListId($intersect);
        }

        $page = (int)$this->_getParam('page');
        if ($page < 1) {
           $page = 1;
        }

        $rows = (int)$this->_getParam('rows');
        if ($rows < 1) {
            $rows = Workset_Model_Object_Abstract::ROWS_LIMIT;
        }

        $cols = $this->_helper->application->getList('cols', true);

        $order = $this->_helper->application->getSortOrder();

		$filter = $this->_getParam('filters');

        $jqGrid = $this->_helper->JQueryGrid;
		$filter = $jqGrid->getFilter($filter, $this->_actionConfig['jqgrid_comment_col_model']);

        if ($diff) {
            $filter['id not in(?)'] = $diff;
        }

        if ($intersect) {
            $filter['id in(?)'] = $intersect;
        }

        $colNames = $this->_helper->utils->arrayValues(
            $this->_actionConfig['jqgrid_comment_col_model'], 'index', 1
        );

        if ($cols) {
            $cols = array_intersect($colNames, $cols);
        } else {
            $cols = $colNames;
        }

        $items = Materials_Model_Comment::getAll($filter, $order, $rows, $page, true);

        $jqGrid->addColumnFormatter('created', function($value) {
            return timestampToDatetime($value);
        });

        $records = $jqGrid->getRecords(
            $items, $page, ceil($items->getTotalCount() / $rows),
            $items->getTotalCount(), $cols
        );

        $this->_helper->json($records, true);
	}

    function addCommentAction() {
        $type = 'comment';
		$oper = $this->_getParam('oper');
        $outerEdit = !empty($oper) && $this->_request->isXmlHttpRequest() ? true : false;

        if ($outerEdit) {
            $this->_helper->viewRenderer->setNoRender(true);
        }

        $materialId = (int)$this->_getParam('nodeid');

        $formConfig = $this->_helper->moduleConfig("forms/{$type}_add");
        $form = new Materials_Form_Comment($formConfig);

		//транслятор формы
        $form->setTranslator(
            $this->_translate,
            $this->_helper->moduleConfig->getConfig(array('lang', $this->_locale, 'validators'), null, true)
        );

        if ($this->_request->isPost()) {
			try {

				$post = $this->_request->getPost();

				//редактирование через внешнюю форму (jqGrid)
				if ($outerEdit) {
					$post = $this->_helper->utils->addPrefix($post, $type);
				}

				if ($materialId > 0) {
					$post['comment_material_id'] = $materialId;
				}

				if ($form->isValid($post)) {
					$values = $form->getValues();
					$values = $this->_helper->utils->stripPrefix($values, $type);

					$comment = Materials_Model_Comment::create($values);
					$comment->save();

					if (!$this->_request->isXmlHttpRequest()) {
						$backUrl = $this->_getParam('backurl');
						if ($backUrl) {
							$this->_redirect($backUrl);
						} else {
							$this->_helper->redirector->gotoSimple('list-' . $type);
						}
					} else {
						return;
					}
				}

				throw new Workset_Model_Exception($form->getCustomMessages(Workset_Form::ERROR_CODE), Workset_Form::ERROR_CODE);

			} catch (Zend_Exception $e) {
                $this->_helper->application->throwException($e, null, false);
            }
        }

        $this->view->form = $form;
		$this->view->backurl = $this->_helper->url('list-'.$type);
    }

	function editCommentAction() {

		$type = "comment";

        $id = (int)$this->_getParam('id');

		$comment = Materials_Model_Comment::getInstance($id);

        $oper = $this->_getParam('oper');
        $outerEdit = !empty($oper) && $this->_request->isXmlHttpRequest() ? true : false;

        if ($outerEdit) {
            $this->_helper->viewRenderer->setNoRender(true);
        }

        $formConfig = $this->_helper->moduleConfig("forms/{$type}_edit");
        $form = new Workset_Form($formConfig);

        //транслятор формы
        $form->setTranslator(
            $this->_translate,
            $this->_helper->moduleConfig->getConfig(array('lang', $this->_locale, 'validators'), null, true)
        );

        if ($this->_request->isPost()) {
            try {
                $post = $this->_request->getPost();

                //редактирование через внешнбб форму (jqGrid)
                if ($outerEdit) {
                    $post = $this->_helper->utils->addPrefix($post, $type);
                }

                if ($form->isValid($post)) {

                    $values = $form->getValues();
                    $values = $this->_helper->utils->stripPrefix($values, $type);

                    $comment->setData($values);
                    $comment->save();

                    if (!$this->_request->isXmlHttpRequest()) {
						$backUrl = $this->_getParam('backurl');
						if ($backUrl) {
							$this->_redirect($backUrl);
						} else {
							$this->_helper->redirector->gotoSimple('list-' . $type);
						}
                    } else {
                        return;
                    }
                }

                throw new Workset_Model_Exception($form->getCustomMessages(Workset_Form::ERROR_CODE), Workset_Form::ERROR_CODE);

            } catch (Zend_Exception $e) {
                $this->_helper->application->throwException($e, null, false);
            }
        } else {
            foreach ($comment->toArray() as $key => $value) {
                $key = $type.'_'.$key;
                if ($element = $form->getElement($key)) {
                    $element->setValue($value);
                }
            }
        }

		$this->view->backurl = $this->_helper->url('list-'.$type);
        $this->view->form = $form;
        $this->render('add-'.$type);
    }

	function deleteCommentAction() {
 		$type = "comment";

        $this->_helper->viewRenderer->setNoRender(true);

        $listId = $this->_helper->application->getListId('id', true);

        if (empty($listId)) {
            throw $this->_helper->application->throwException(null, 404);
        }

        $filter = array('id in(?)' => $listId);

        $items = Materials_Model_Comment::getAll($filter);

        try {
            foreach ($items as $object) {
                $object->delete();
            }
        } catch (Zend_Exception $e) {
            $this->_helper->application->throwException($e);
        }

        if (!$this->_request->isXmlHttpRequest()) {
            $redirect = $this->_helper->url('list-'.$type);
            $this->_redirect($redirect);
        }
    }

	public function ajaxCommentOperationsAction() {
        $this->_helper->viewRenderer->setNoRender(true);

        $actionSwitcher = new Workset_Controller_Plugin_ActionSwitcher('oper', array(
            'del' => array(
                'action' => 'delete-comment',
            ),
            'edit' => array(
                'action' => 'edit-comment'
            ),
            'add' => array(
                'action' => 'add-comment'
            ),
        ));

        $this->getFrontController()->registerPlugin($actionSwitcher);
        $this->_setParam('handlePostDispatch', false);
    }

    function listLabelAction() {
        $this->view->jqgrid = $this->view->JQueryGrid()
                ->setTableId('labelList')
                ->setPagerId('labelPager')
                ->setOptions(array(
                    'caption' => $this->_actionConfig['jqgrid_label_caption'],
                    'url' => $this->_helper->url('list-label-model'),
                    'mtype' => 'GET',
                    'colNames' => array_values($this->_actionConfig['jqgrid_label_col_names']),
                    'colModel' => array_values($this->_actionConfig['jqgrid_label_col_model']),
                    'sortname' => 'id',
                    'sortorder' => "desc",
                    'viewrecords' => true,
                    'multiselect' => true,
                    'editurl'   => $this->_helper->url('ajax-label-operations'),
                    'autowidth' => true,
                    'rowNum' => 20,
                ))
                ->enableNavGrid(array(
                    'add' => true,
                    'edit' => true,
                    'refresh' => true,
                    'search' => true,
                    'del' => true
                ));

		$this->view->jqgrid->jsObject = $this->_helper->application->jsFunctionName();
	}

	function listLabelModelAction() {
		//выбирать только несовпадающие элементы
        $diff = $this->_getParam('diff');
        if ($diff) {
            $diff = $this->_helper->application->getListId($diff);
        }

        //выбирать только совпадающие элементы
        $intersect = $this->_getParam('intersect');
        if ($intersect) {
            $intersect = $this->_helper->application->getListId($intersect);
        }

        $page = (int)$this->_getParam('page');
        if ($page < 1) {
           $page = 1;
        }

        $rows = (int)$this->_getParam('rows');
        if ($rows < 1) {
            $rows = Workset_Model_Object_Abstract::ROWS_LIMIT;
        }

        $cols = $this->_helper->application->getList('cols', true);

        $order = $this->_helper->application->getSortOrder();

		$filter = $this->_getParam('filters');
		$filter = $this->_helper->JQueryGrid->getFilter($filter, $this->_actionConfig['jqgrid_label_col_model']);

        if ($diff) {
            $filter['id not in(?)'] = $diff;
        }

        if ($intersect) {
            $filter['id in(?)'] = $intersect;
        }

        $colNames = $this->_helper->utils->arrayValues(
            $this->_actionConfig['jqgrid_label_col_model'], 'index', 1
        );

        if ($cols) {
            $cols = array_intersect($colNames, $cols);
        } else {
            $cols = $colNames;
        }

        $items = Materials_Model_Label::getAll($filter, $order, $rows, $page, true);

        $records = $this->_helper->JQueryGrid(
            $items, $page, ceil($items->getTotalCount() / $rows),
            $items->getTotalCount(), $cols
        );

        $this->_helper->json($records, true);
	}

    function addLabelAction() {
        $type = 'label';
		$oper = $this->_getParam('oper');
        $outerEdit = !empty($oper) && $this->_request->isXmlHttpRequest() ? true : false;

        if ($outerEdit) {
            $this->_helper->viewRenderer->setNoRender(true);
        }

        $formConfig = $this->_helper->moduleConfig("forms/{$type}");
        $form = new Materials_Form_Label($formConfig);

		//транслятор формы
        $form->setTranslator(
            $this->_translate,
            $this->_helper->moduleConfig->getConfig(array('lang', $this->_locale, 'validators'), null, true)
        );

        if ($this->_request->isPost()) {
			try {

				$post = $this->_request->getPost();

				//редактирование через внешнюю форму (jqGrid)
				if ($outerEdit) {
					$post = $this->_helper->utils->addPrefix($post, $type);
				}

				if ($form->isValid($post)) {
					$values = $form->getValues();
					$values = $this->_helper->utils->stripPrefix($values, $type);

					$label = Materials_Model_Label::create($values);
					$label->save();

					if (!$this->_request->isXmlHttpRequest()) {
						$backUrl = $this->_getParam('backurl');
						if ($backUrl) {
							$this->_redirect($backUrl);
						} else {
							$this->_helper->redirector->gotoSimple('list-' . $type);
						}
					} else {
						return;
					}
				}

				throw new Workset_Model_Exception($form->getCustomMessages(Workset_Form::ERROR_CODE), Workset_Form::ERROR_CODE);

			} catch (Zend_Exception $e) {
                $this->_helper->application->throwException($e, null, false);
            }
        }

        $this->view->form = $form;
		$this->view->backurl = $this->_helper->url('list-'.$type);
    }

	function editLabelAction() {
        $type = 'label';

		$label = $this->_helper->application->getLabel('id', true);

        $oper = $this->_getParam('oper');
        $outerEdit = !empty($oper) && $this->_request->isXmlHttpRequest() ? true : false;

        if ($outerEdit) {
            $this->_helper->viewRenderer->setNoRender(true);
        }

        $formConfig = $this->_helper->moduleConfig("forms/{$type}");
        $form = new Workset_Form($formConfig);

        //транслятор формы
        $form->setTranslator(
            $this->_translate,
            $this->_helper->moduleConfig->getConfig(array('lang', $this->_locale, 'validators'), null, true)
        );

        if ($this->_request->isPost()) {
            try {
                $post = $this->_request->getPost();

                //редактирование через внешнбб форму (jqGrid)
                if ($outerEdit) {
                    $post = $this->_helper->utils->addPrefix($post, $type);
                }

                if ($form->isValid($post)) {

                    $values = $form->getValues();
                    $values = $this->_helper->utils->stripPrefix($values, $type);

                    $label->setData($values);
                    $label->save();

                    if (!$this->_request->isXmlHttpRequest()) {
						$backUrl = $this->_getParam('backurl');
						if ($backUrl) {
							$this->_redirect($backUrl);
						} else {
							$this->_helper->redirector->gotoSimple('list-' . $type);
						}
                    } else {
                        return;
                    }
                }

                throw new Workset_Model_Exception($form->getCustomMessages(Workset_Form::ERROR_CODE), Workset_Form::ERROR_CODE);

            } catch (Zend_Exception $e) {
                $this->_helper->application->throwException($e, null, false);
            }
        } else {
            foreach ($label->toArray() as $key => $value) {
                $key = $type.'_'.$key;
                if ($element = $form->getElement($key)) {
                    $element->setValue($value);
                }
            }
        }

		$this->view->backurl = $this->_helper->url('list-'.$type);
        $this->view->form = $form;
        $this->render('add-'.$type);
    }

	function deleteLabelAction() {
 		$type = 'label';
        $this->_helper->viewRenderer->setNoRender(true);

        $listId = $this->_helper->application->getListId('id', true);

        if (empty($listId)) {
            throw $this->_helper->application->throwException(null, 404);
        }

        $filter = array('id in(?)' => $listId);

        $items = Materials_Model_Label::getAll($filter);

        try {
            foreach ($items as $object) {
                $object->delete();
            }
        } catch (Zend_Exception $e) {
            $this->_helper->application->throwException($e);
        }

        if (!$this->_request->isXmlHttpRequest()) {
            $redirect = $this->_helper->url('list-'.$type);
            $this->_redirect($redirect);
        }
    }

    public function ajaxLabelOperationsAction() {
        $this->_helper->viewRenderer->setNoRender(true);

        $actionSwitcher = new Workset_Controller_Plugin_ActionSwitcher('oper', array(
            'del' => array(
                'action' => 'delete-label',
            ),
            'edit' => array(
                'action' => 'edit-label'
            ),
            'add' => array(
                'action' => 'add-label'
            ),
        ));

        $this->getFrontController()->registerPlugin($actionSwitcher);
        $this->_setParam('handlePostDispatch', false);
    }

    function selectCategoryAction() {
        $parentId = (int)$this->_getParam('nodeid');
        $backurl = $this->_getParam('backurl');
        $filter = array();

        if ($parentId > 0) {
            $filter["parent_id = ?"] = $parentId;
        }

        if (!$backurl) {
            $backurl = $this->_request->getRequestUri();
        }

        $uri = $this->_helper->httpUri($backurl);
		$redirectParams = $uri->getQueryAsArray();

        if (empty($redirectParams)) {
            $redirectParams = null;
        }

		$uri->setQuery(null);
		$redirectUrl = $uri->getUri();

        //url для редактирования
        if (isset($this->_actionConfig['jqgrid_category_edit_url'])) {
            $editUrlParams = $this->_actionConfig['jqgrid_category_edit_url'];
        } else {
            $editUrlParams = array('action' => 'ajax-category-operations');
        }

        $editUrl = $this->_helper->url($editUrlParams);

		$modelUrl = $this->_helper->url('list-category-model');

		$gridOptions = array(
            'caption' => $this->_actionConfig['jqgrid_category_caption'],
            'url' => $modelUrl,
            'editurl' => $editUrl,
            'mtype' => 'GET',
            'colNames' => array_values($this->_actionConfig['jqgrid_category_col_names']),
            'colModel' => array_values($this->_actionConfig['jqgrid_category_col_model']),
            'sortname' => 'id',
            'sortorder' => "desc",
            'viewrecords' => true,
			'treeGrid' => true,
            'treeGridModel' => 'adjacency',
            'treedatatype' => 'json',
            'ExpandColumn' => 'name',
            'ExpandColClick' => true,
            'autowidth' => true,
            'rowNum' => 50,
            'viewsortcols' => array('name', 'display_title', 'code', 'id'),
			'ondblClickRow' => new Zend_Json_Expr($this->_helper->application->jsFunction('selectRow', array('id'), true)),
        );

		$tableId = 'categoryList';
        $pageId = 'categoryPager';

        //ссылка на объект помошника
        $this->view->grid = $this->view
                ->JQueryGrid()
                ->setTableId($tableId)
                ->setPagerId($pageId)
                ->setOptions($gridOptions)
				->enableNavGrid(array(
                    'edit' => false,
					'add' => false,
					'del' => false
                ))
                ->addNavButton('btn_select', array(
                    'buttonicon' => 'ui-icon-circle-check',
                    'caption' => 'Выбрать',
                    'title' => 'Выбрать раздел',
                    'position' => 'last',
                    'onClickButton' => new Zend_Json_Expr($this->_helper->application->jsFunction('selectSingleRow', null, true)),
                ))
                ->addNavButton('btn_add', array(
                    'buttonicon' => 'ui-icon-plus',
                    'caption' => '',
                    'title' => 'Создать новый раздел',
                    'position' => 'first',
                    'onClickButton' => new Zend_Json_Expr($this->_helper->application->jsFunction('createRow', null, true)),
                ));

		$this->view->jsObject = $this->_helper->application->jsFunctionName();
		$this->view->redirectUrl = $redirectUrl;
		$this->view->redirectParams = Zend_Json::encode($redirectParams);

    }

}

?>